<?php
namespace app\common\model;
use think\Model;
class ReplyMenuModel extends BaseReplyModel
{
    protected $table="zbc_reply_menu";

    public function getWithSubMenu($size=3){
        $query=$this->with("subMenu",["article"=>function($query){
            $query->with("assets");
        }]);
        $query=$query->where("parent",null);

        if($size){
            $query=$query->limit($size);
        }
        
        return $query->select();   
    }

    public function createOrUpdate($params){
        
        
        $result=null;
        $db=$this->db(false);
        $db->startTrans();

        try{

            $menu=$this->createMenus($params);
            if(count($menu["button"])>0){
                $subResult=$this->getMenuControl()->create($menu);
            }else{
                $subResult=$this->getMenuControl()->delete();
            }
            
            $menus=$this->getWithSubMenu(0);
    
            $ids=[];
            foreach($menus as $key=>$item){
                $ids[$item->id]=true;
                foreach($item->subMenu as $subkey=>$subitem){
                    $ids[$subitem->id]=true;
                }
            }

            $subData=[];
            
            foreach($params as $key=>$menuItem)
            {
                $isUpdate=array_key_exists("id",$menuItem);
                if($isUpdate && array_key_exists($menuItem["id"],$ids))
                {
                    $menuId=$menuItem["id"];
                    $ids[$menuId]=false;
                    if(!array_key_exists("subMenu",$menuItem) || !$menuId) break;
                    $subData[$menuId]=["update"=>[],"add"=>[]];
                    foreach($menuItem["subMenu"] as $subkey=>$subitem)
                    {
                        $isUpdate=array_key_exists("id",$subitem);
                        if($isUpdate && array_key_exists($subitem["id"],$ids))
                        {
                            $ids[$subitem["id"]]=false;
                            $subData[$menuId]["update"]=array_merge($subData[$menuId]["update"],[$subitem]);
                        }else{
                            $subData[$menuId]["add"]=array_merge($subData[$menuId]["add"],[$subitem]);
                        }
                    }
                } 
            }

            $result=$this->saveAll($params);
            foreach($result as $saveMenu){
                if(array_key_exists($saveMenu->id,$subData)){
                    $subitems=$subData[$saveMenu->id];
                    if(count($subitems["update"])){
                        $saveMenu->subMenu()->saveAll($subitems["update"],$saveMenu->id);  
                    }
                    if(count($subitems["add"])){
                        $saveMenu->subMenu()->saveAll($subitems["add"]);  
                    }
                }else{
                    $saveMenu->subMenu()->saveAll($saveMenu->subMenu);  
                }
            }

            // $sql=$this->getLastSql();
            $ids=array_filter($ids);
            if(count($ids)>0){
                $ids=array_keys($ids);
                $isDelete=self::where("id","in",$ids)->delete();

                if($isDelete){

                }
            }
            $db->commit();
        }
        catch (\Exception $ex){
            $db->rollback();
            $result=null;
        }

        return $result;
    }


    public function subMenu(){
        return $this->hasMany("ReplyMenuModel","parent","id");
    }

    public function article(){
        return $this->belongsTo("ReplyArticleModel","mediaId","newsId")
        ->bind("title")
        ->setEagerlyType(0);
    }

    private function createMenus($params){
        $params=array_splice($params,0,3);
        $menuItem=[];
        $index=0;
        foreach($params as $key=>$menu){
            $type=$menu["type"];
            $item=$this->createMenuItem($type,$menu);
            if($item){
                if(array_key_exists("subMenu",$menu)){
                    $subMenu=$menu["subMenu"];
                    $item["sub_button"]=$this->createSubMenu($subMenu);
                }

                $menuItem[$index]=$item;
            }
            $index++;
        }

        return ["button"=>$menuItem];
    }

    private function createSubMenu($params){
        $subMenus=[];
        $index=0;
        foreach($params as $item=>$menu){
            $type=$menu["type"];
            $menuItem=$this->createMenuItem($type,$menu);
            if($menuItem){
                $subMenus[$index]=$menuItem;
                $index++;
            }
        }
        return $subMenus;
    }

    private function createMenuItem($type,$params){
        $menu=[
            "name"=>$params["name"],
            "type"=>$type
        ];
        
        switch($type){
            case "click":
                $menu["key"]=$params["keyword"];
                break;
            case "view":
                $menu["url"]=$params["url"];
                break;
            case "miniprogram":
                $menu["appid"]=$params["appid"];
                $menu["url"]=$params["appUrl"];
                $menu["pagepath"]=$params["appPath"];
                break;
            case "view_limited":
                $menu["media_id"]=$params["mediaId"];
                break;
            default:
                $menu=null;
                break;
        }

        return $menu;
    }
}